package com.cuitrip.business.bill;

import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.cuitrip.apiservice.OrderBusiness;
import com.cuitrip.apiservice.model.ApiManager;
import com.cuitrip.business.login.LoginInstance;
import com.cuitrip.component.RecyclerItemClickListener;
import com.cuitrip.component.page.SimpleEmptyFragmentActivity;
import com.cuitrip.service.R;
import com.cuitrip.util.PlatformUtil;
import com.cuitrip.util.ResourceUtil;
import com.cuitrip.util.time.InputTime;
import com.cuitrip.util.time.OutputTime;
import com.cuitrip.util.time.TimeUtil;
import com.cuitrip.util.track.TrackUtil;
import com.lab.app.customui.CustomUiConfig;
import com.lab.app.customui.CustomUiFragmentActivity;
import com.lab.component.list.adapter.CTRecyclerAdapter;
import com.lab.component.list.viewholder.CTRecycleViewHolder;
import com.lab.network.model.CtApiResponse;
import com.lab.network.model.IProxyCallback;
import com.lab.network.proxy.ApiProxy;
import com.lab.network.proxy.ApiProxyBuilder;
import com.lab.network.proxy.ApiProxyCallBack;
import com.lab.utils.ImageHelper;
import com.lab.utils.LogHelper;
import com.lab.utils.MessageUtils;
import com.lab.utils.NumberUtils;
import com.lab.utils.Utils;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import de.hdodenhof.circleimageview.CircleImageView;

/**
 * Created by baziii on 15/8/18.
 */
public class BillActivity extends CustomUiFragmentActivity {
    public static final String TAG = "BaseVerticalListActivity";
    public static final int DEFAULT_SIZE = 10;
    private static final int CODE_GET_CASH = 200;
    @Bind(R.id.ct_recycler_view)
    protected RecyclerView mRecyclerView;
    @Bind(R.id.ct_swipe_refresh_layout)
    protected SwipeRefreshLayout mSwipeRefreshLayout;
    LinearLayoutManager mLayoutManager;
    @Bind(R.id.amount)
    TextView amount;
    @Bind(R.id.bill_money_type)
    TextView billMoneyType;
    //包括刷新和loadMore
    boolean loading = false;
    boolean hasMore = true;
    boolean isResumeRefresh = false;
    BillAdapter adapter = new BillAdapter();
    Bills bills;
    ApiProxy apiProxy;
    private int index = 0;
    protected RecyclerView.OnScrollListener onScrollListener = new RecyclerView.OnScrollListener() {

        @Override
        public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
            super.onScrolled(recyclerView, dx, dy);
            int pastVisiblesItems, visibleItemCount, totalItemCount;

            visibleItemCount = mLayoutManager.getChildCount();
            totalItemCount = mLayoutManager.getItemCount();
            pastVisiblesItems = mLayoutManager.findFirstVisibleItemPosition();
            if (hasMore && !loading) {
                if ((visibleItemCount + pastVisiblesItems) >= totalItemCount) {
                    requestPresentLoadMore();
                }
            }
        }
    };
    protected SwipeRefreshLayout.OnRefreshListener onRefreshListener = new SwipeRefreshLayout.OnRefreshListener() {
        @Override
        public void onRefresh() {
            LogHelper.e(TAG, "ui onrefresh call");
            requestPresentRefresh();
        }
    };
    IProxyCallback callBack = new ApiProxyCallBack<Bills>() {

        @Override
        public boolean onSuccess(Bills data, CtApiResponse response) {
            LogHelper.e(TAG, " suc" + String.valueOf(response.result));
            if (data != null && data instanceof Bills) {
                bills = data;
                LogHelper.e(TAG, " res " + String.valueOf(response.result));
                amount.setText(NumberUtils.getMoneyFormat(bills.balance));
                billMoneyType.setText(bills.moneyType.toUpperCase());
                if (index == 0) {
                    adapter.setBillDatas(bills.getLists());
                } else {
                    if (bills.getLists() != null) {
                        adapter.getBillDatas().addAll(bills.getLists());
                    }
                }
                adapter.notifyDataSetChanged();
            }
            hideLoading();
            loading = false;
            return super.onSuccess(data, response);
        }

        @Override
        public boolean onFaild(CtApiResponse response) {
            LogHelper.e(TAG, " failed");
            String msg;
            if (response != null && !TextUtils.isEmpty(response.msg)) {
                msg = response.msg;
            } else {
                msg = PlatformUtil.getInstance().getString(R.string.feedback_data_err);
            }
            MessageUtils.showToast(msg);
            hideLoading();
            loading = false;
            return false;
        }
    };

    public static void start(Context context) {
        if (context != null) {
            context.startActivity(new Intent(context, BillActivity.class));
        }
    }

    public void getCash() {
        if (bills != null) {
            BillCashActivity.start(this, bills.getBalance(), bills.getMoneyType(), CODE_GET_CASH);
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState,R.layout.bill);
    }

    @Override
    public void initView() {
        ButterKnife.bind(this);
        ((TextView) findViewById(R.id.balanceExplain)).setTextSize(21.f);
        mLayoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
        mRecyclerView.setLayoutManager(mLayoutManager);
        mRecyclerView.setAdapter(adapter);
    }

    @Override
    public void initListener() {
        mRecyclerView.addOnScrollListener(onScrollListener);
        mSwipeRefreshLayout.setOnRefreshListener(onRefreshListener);
        mRecyclerView.addOnItemTouchListener(new RecyclerItemClickListener(this, new RecyclerItemClickListener.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                BillData data = adapter.getBillDatas().get(position);
                int type = data.getType();
                // 账单类型： 1 入账 2 提现 3 奖励
                Bundle args = new Bundle();
                String billId = data.getBillId();
                args.putString("billId", billId);
                switch (type) {
                    case 1:
                        TrackUtil.trackScreenName("/insider/transactions/detail");
                        SimpleEmptyFragmentActivity.startFragmentActivity(BillActivity.this, BillDetailFragment.class, args);
                        break;
                    case 2://提现
                        TrackUtil.trackScreenName("/insider/transactions/withdraw");
                        SimpleEmptyFragmentActivity.startFragmentActivity(BillActivity.this, CashDetailFragment.class, args);
                        break;
                    case 3://奖励
                        //金额、币种、时间
                        String money=data.getMoney();
                        String moneyType=data.getMoneyType();
                        String time=Long.toString(data.getGmtCreated());
                        RewardFragment.startFragment(BillActivity.this,money, moneyType, time);
                        break;
                }
            }
        }));
        apiProxy= ApiProxyBuilder.getBuilder().addApiCallBack(ApiManager.GET_BILLS,callBack).build();
        requestPresentRefresh();
    }

    @Override
    protected void onResume() {
        super.onResume();
        LogHelper.e(TAG, " is ui show refresh:" + mSwipeRefreshLayout.isRefreshing());
        if (mSwipeRefreshLayout.isRefreshing()) {
            mSwipeRefreshLayout.setRefreshing(false);
            isResumeRefresh = true;
            mSwipeRefreshLayout.postDelayed(new Runnable() {
                @Override
                public void run() {
                    if (isResumeRefresh) {
                        mSwipeRefreshLayout.setRefreshing(true);
                    }
                }
            }, 300);
        }
    }

    @Override
    public void showLoading() {
        mSwipeRefreshLayout.setRefreshing(true);
    }

    @Override
    public void hideLoading() {
        isResumeRefresh = false;
        mSwipeRefreshLayout.setRefreshing(false);
    }

    public void requestPresentRefresh() {
        if(loading){
            return;
        }
        showLoading();
        loading = true;
        index=0;
        requestLoadData();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode==CODE_GET_CASH){
            requestPresentRefresh();
        }
    }

    public void requestPresentLoadMore() {
        if(loading){
            return;
        }
        showLoading();
        loading = true;
        index++;
        requestLoadData();
    }

    private void requestLoadData() {
        OrderBusiness.getBills(apiProxy,index*DEFAULT_SIZE,DEFAULT_SIZE);}

    @OnClick(R.id.balanceExplain)
    public void showBalanceExplain() {
        ExplainActivity.startActivityBy(this, ExplainActivity.SHOW_INFO_ABOUT_BALANCE);
    }

    @OnClick(R.id.ratingToday)
    public void showRating() {
        ExplainActivity.startActivityBy(this, ExplainActivity.SHOW_INFO_ABOUT_RATING);
    }

    @Override
    public boolean initCloseTopBar() {
        return false;
    }

    @Override
    public CustomUiConfig initCustomUiConfig() {
        CustomUiConfig config=new CustomUiConfig();
        config.mTopbarLeftAreaName=getString(R.string.back_icon);
        config.mTopbarMiddleAreaName=getString(R.string.transaction);
        config.mTopbarRightAreaName=getString(R.string.withdraw);
        config.mRightStyle= CustomUiConfig.AreaStyle.TEXT_STYLE;
        return config;
    }

    @Override
    public void onTopbarLeftPress() {
        onBackPressed();
    }

    @Override
    public void onTopbarRightPress() {
        getCash();
    }

    public static class BillItemView extends CTRecycleViewHolder<BillData> {

        @Bind(R.id.image)
        CircleImageView image;
        @Bind(R.id.billName)
        TextView billName;
        @Bind(R.id.time)
        TextView time;
        @Bind(R.id.moneyType)
        TextView moneyType;
        @Bind(R.id.money)
        TextView money;
        @Bind(R.id.cashCurrency)
        TextView cashCurrency;
        @Bind(R.id.cashPrice)
        TextView cashPrice;
        @Bind(R.id.billUser)
        TextView billUser;
        @Bind(R.id.status)
        TextView status;

        public BillItemView(View itemView) {
            super(itemView);
            ButterKnife.bind(this, itemView);
        }


        public void render(BillData data, int position) {
            // 账单类型： 1 入账 2 提现 3 奖励
            Resources resources=itemView.getResources();
            time.setText(
                    TimeUtil.formatTime(
                            InputTime.build(data.getGmtCreated()),
                            OutputTime.getLocalInstance(OutputTime.OutputType.Type_DAY))
            );
            switch (data.getType()){
                case 1:
                    cashCurrency.setTextColor(ResourceUtil.getThemeColor());
                    cashPrice.setTextColor(ResourceUtil.getThemeColor());
                    ImageHelper.displayPersonImage(data.getHeadPic(), image, null);
                    billName.setText(data.getTitle());
                    billUser.setText(data.getUserNick());
                    cashPrice.setText(NumberUtils.getMoneyFormat(data.getCashPrice()));
                    status.setVisibility(View.INVISIBLE);
                    break;
                case 2:
                    boolean flag= data.getStatus() == 3;
                    cashCurrency.setTextColor(flag ? resources.getColor(R.color.qiaomai_7c706e) : resources.getColor(R.color.apple_7ecc1e));
                    cashPrice.setTextColor(flag?resources.getColor(R.color.qiaomai_7c706e):resources.getColor(R.color.apple_7ecc1e));
                    ImageHelper.displayPersonImage(LoginInstance.getInstance().getUserInfo().getHeadPic(), image, null);
                    billName.setText(R.string.withdraw);
                    billUser.setText(Utils.formatPaypal(data.getPaypal()));
                    cashPrice.setText("-"+NumberUtils.getMoneyFormat(data.getCashPrice()));
                    status.setVisibility(View.VISIBLE);
                    status.setText(data.getStatusString(status.getContext()));
                    break;
                case 3:
                    cashCurrency.setTextColor(ResourceUtil.getThemeColor());
                    cashPrice.setTextColor(ResourceUtil.getThemeColor());
                    image.setImageResource(R.drawable.ct_icon);
                    billName.setText(R.string.transaction_attribute_type_reward);
                    billUser.setText(R.string.app_name);
                    cashPrice.setText(NumberUtils.getMoneyFormat(data.getCashPrice()));
                    status.setVisibility(View.INVISIBLE);
                    break;
            }
            cashCurrency.setText(data.getCashCurrency());
            money.setHint("0.00");
            money.setText(NumberUtils.getMoneyFormat(data.getMoney()));
            moneyType.setText(data.getMoneyType());
            if (data.getCashCurrency().equals(data.getMoneyType())){
                money.setVisibility(View.INVISIBLE);
                moneyType.setVisibility(View.INVISIBLE);
            } else {
                money.setVisibility(View.VISIBLE);
                moneyType.setVisibility(View.VISIBLE);
            }
        }

        public String getUpCasedMoneyType(BillData data) {
            return (TextUtils.isEmpty(data.getMoneyType()) ? "" : data.getMoneyType().toUpperCase());
        }
    }

    public class BillAdapter extends CTRecyclerAdapter<BillItemView> {

        private List<BillData> billDatas = new ArrayList<>();

        public List<BillData> getBillDatas() {
            return billDatas;
        }

        public void setBillDatas(List<BillData> billDatas) {
            if (billDatas == null) {
                billDatas = new ArrayList<>();
            }
            this.billDatas = billDatas;
            notifyDataSetChanged();
        }

        public BillItemView newViewHolder(ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.bill_item, null);
            BillItemView vh = new BillItemView(view);
            return vh;
        }

        @Override
        public void onBindViewHolder(BillItemView holder, int position) {
            holder.render(billDatas.get(position), position);
        }

        @Override
        public int getItemCount() {
            return billDatas == null ? 0 : billDatas.size();
        }
    }
}
